<template>
  <div class="app-container contarctbill">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名称" prop="fee">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入客户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同编号" prop="contarctId">
        <el-input
          v-model="queryParams.contarctCode"
          placeholder="请输入合同编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同名称" prop="contarctName">
        <el-input
          v-model="queryParams.contarctName"
          placeholder="请输入归属合同名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="付款截至月份" prop="billMonth">
        <el-date-picker
          v-model="queryParams.billMonth"
          type="month"
          placeholder="选择月">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="账单状态" prop="isover">
        <el-radio-group v-model="queryParams.isover" size="small">
          <el-radio-button label="0">未结算</el-radio-button>
          <el-radio-button label="1">已结算</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="账单类型" prop="billType">
        <el-radio-group v-model="queryParams.billType" size="small">
          <el-radio-button label="0">固定账单</el-radio-button>
          <el-radio-button label="1">其它账单</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索账单</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div style="display: flex;justify-content:space-between">
      <el-row :gutter="10" class="mb8" style="width:auto">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['contarctbill:contarctbill:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['contarctbill:contarctbill:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['contarctbill:contarctbill:remove']"
          >删除
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>
    <el-table v-loading="loading" :data="contarctbillList" @selection-change="handleSelectionChange">
      <el-table-column fixed type="selection" width="55" align="center"/>
      <el-table-column label="账期" align="center" prop="contarctPlandate">
        <template slot-scope="scope">
          <span>{{ scope.row.contarctPlandate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.houseContarct?scope.row.houseContarct.companyName:"" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.houseContarct?scope.row.houseContarct.contactName:"" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同编号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.houseContarct?scope.row.houseContarct.contarctCode:"" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物管合同号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.houseContarct? scope.row.houseContarct.propertyCode:"" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账单类型" align="center" prop="billType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bill_type" :value="scope.row.billType"/>
        </template>
      </el-table-column>
      <el-table-column label="账单状态" align="center" prop="isover">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bill_over_type" :value="scope.row.isover"/>
        </template>
      </el-table-column>
      <el-table-column label="收款截止日" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="应收租金(元)" align="center" prop="fee">
        <template slot-scope="scope">
          <span>{{ scope.row.billShould }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已收租金(元)" align="center" prop="fee">
        <template slot-scope="scope">
          <span>{{ scope.row.billAlready }}</span>
        </template>
      </el-table-column>

      <el-table-column width="200" fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-show="scope.row.isover === 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['contarctbill:contarctbill:edit']"
          >确认收款
          </el-button>
          <el-button
            v-show="scope.row.isover === 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="seeBill(scope.row)"
            v-hasPermi="['contarctbill:contarctbill:edit']"
          >查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改账单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="应收收费" prop="fee">
          <el-input v-model="form.fee" placeholder="请输入应收收费"/>
        </el-form-item>

        <el-form-item label="归属合同id" prop="contarctId">
          <el-input v-model="form.contarctId" placeholder="请输入归属合同id"/>
        </el-form-item>
        <el-form-item label="计划备注" prop="contarctPlanbz">
          <el-input v-model="form.contarctPlanbz" placeholder="请输入计划备注"/>
        </el-form-item>
        <el-form-item label="计费周期" prop="contarctPlandate">
          <el-input v-model="form.contarctPlandate" placeholder="请输入计费周期"/>
        </el-form-item>
        <el-form-item label="用于处理是否显示在计划管理  0代表未结算完成，1代表已结算完毕" prop="isover">
          <el-select v-model="form.isover" placeholder="请选择用于处理是否显示在计划管理  0代表未结算完成，1代表已结算完毕">
            <el-option
              v-for="dict in dict.type.settlement_over"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="已收款金额" prop="ysfee">
          <el-input v-model="form.ysfee" placeholder="请输入已收款金额"/>
        </el-form-item>
        <el-form-item label="计费结束时间" prop="contarctPlanEnddate">
          <el-date-picker clearable size="small"
                          v-model="form.contarctPlanEnddate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择计费结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计费开始时间" prop="contarctPlanStartdate">
          <el-date-picker clearable size="small"
                          v-model="form.contarctPlanStartdate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择计费开始时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="确认收款" :visible.sync="proceedsopen" width="600px" append-to-body>
      <el-form ref="form" :model="proceedsform" :rules="proceedsrules" label-width="80px">
        <div class="proceedstitle">合计应收费用</div>
        <el-table class="proceedsTable" v-loading="loading" :data="proceedsList">
          <el-table-column label="收费类型" align="center" prop="type">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.feetypeid" :value="scope.row.feetypeid"/>
            </template>
          </el-table-column>
          <el-table-column label="应收（元）" align="center" prop="receivable">
            <template slot-scope="scope">
              <span>{{ scope.row.fee }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已收（元）" align="center" prop="received">
            <template slot-scope="scope">
              <span>{{ scope.row.ysfee }}</span>
            </template>
          </el-table-column>
          <el-table-column label="待收（元）" align="center" prop="collection">
            <template slot-scope="scope">
              <span>{{ scope.row.fee - scope.row.ysfee }}</span>
            </template>
          </el-table-column>
          <el-table-column label="收到的金额（元）" align="center" width="180">
            <template slot-scope="scope">
              <el-form-item prop="receive" class="receive">
                <el-input v-model="scope.row.receive" placeholder="请输入收到的金额" @blur="validatePass(scope.row,scope.$index)"/>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="proceedscancel">取消</el-button>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="proceedssubmitForm">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>



    <el-dialog title="查看收款项" :visible.sync="proceedsopenonlyRead" width="600px" append-to-body>
      <el-form ref="form" :model="proceedsform" :rules="proceedsrules" label-width="80px">
        <div class="proceedstitle">合计应收费用</div>
        <el-table class="proceedsTable" v-loading="loading" :data="proceedsListonlyRead">
          <el-table-column label="收费类型" align="center" prop="type">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.feetypeid" :value="scope.row.feetypeid"/>
            </template>
          </el-table-column>
          <el-table-column label="应收（元）" align="center" prop="receivable">
            <template slot-scope="scope">
              <span>{{ scope.row.fee }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已收（元）" align="center" prop="received">
            <template slot-scope="scope">
              <span>{{ scope.row.ysfee }}</span>
            </template>
          </el-table-column>
          <el-table-column label="待收（元）" align="center" prop="collection">
            <template slot-scope="scope">
              <span>{{ scope.row.fee - scope.row.ysfee }}</span>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="seeBillCancel">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<style lang="scss">
  .proceedsTable {
    margin: 30px 0;
  }

  .receive .el-form-item__content {
    margin: 0 !important;
  }
</style>
<script>
  import {
    listContarctbill,
    delContarctbill,
    addContarctbill,
    updateContarctbill
  } from "@/api/contarctbill/contarctbill";
  import {payBillToIncome} from "@/api/income/income";
  import {formatDateMonth, formatDate } from "@/utils/index"

  export default {
    name: "Contarctbill",
    dicts: ['bill_type', 'refund_status', 'sys_status', 'settlement_over','feetypeid','bill_over_type'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 账单表格数据
        contarctbillList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          createTime: null,
          fee: null,
          updateTime: null,
          contarctId: null,
          contarctPlanbz: null,
          contarctPlandate: null,
          isover: null,
          ysfee: null,
          contarctPlanEnddate: null,
          contarctPlanStartdate: null,
          refundStatus: null,
          billMonth: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        proceedsopen: false,
        proceedsopenonlyRead: false,
        proceedsform: {
          receive: 0
        },
        proceedsrules: {},
        proceedsList: [],
        proceedsListonlyRead: []
      };
    },
    activated() {
      this.getList();
    },
    created() {
      this.getList();
    },
    methods: {
      validatePass(row,index) {
        if(row.fee - row.ysfee<row.receive){
          this.proceedsList[index].receive=0;
          this.$modal.msgError("收到金额不能大于代收金额");
        }
      },
      /** 查询账单列表 */
      getList() {
        this.loading = true;
        this.queryParams.billMonth = formatDateMonth(this.queryParams.billMonth)
        listContarctbill(this.queryParams).then(response => {
          this.contarctbillList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          createTime: null,
          fee: null,
          updateTime: null,
          contarctId: null,
          createBy: null,
          updateBy: null,
          contarctPlanbz: null,
          contarctPlandate: null,
          isover: null,
          ysfee: null,
          contarctPlanEnddate: null,
          contarctPlanStartdate: null,
          refundStatus: 0,
          status: 0
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加账单";
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      /** 提交按钮 */
      submitForm() {
        var status = this.form.contarctStatus;
        if (status === 5) {
          updateContarct(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else {
          this.open = false;
        }

        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateContarctbill(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addContarctbill(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除账单编号为"' + ids + '"的数据项？').then(function () {
          return delContarctbill(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('contarctbill/contarctbill/export', {
          ...this.queryParams
        }, `contarctbill_${new Date().getTime()}.xlsx`)
      },
      //合同详情
      handleDetail(row) {
        this.$router.push({
          path: "/contarct/ContarctDetails"
        });
      },
      /** 确认收款按钮操作 */
      handleUpdate(row) {
        this.proceedsopen = true;
        this.proceedsList = row.houseContarctIncomes
      },
      // 收款取消
      proceedscancel() {
        this.proceedsopen = false;
      },
      // 收款确定
      proceedssubmitForm() {
        const resList = new Array()
        for (var i = 0; i < this.proceedsList.length; i++) {
          const req = {
            incomeId: this.proceedsList[i].id,
            price: parseFloat((parseFloat(this.proceedsList[i].receive)).toFixed(2))
          }
          resList.push(req)
        }
        payBillToIncome(resList).then(response => {
          this.proceedsopen = false;
          this.getList()
        })
      },
      seeBill(row){
        this.proceedsopenonlyRead = true
        this.proceedsListonlyRead = row.houseContarctIncomes
      },
      seeBillCancel(){
        this.proceedsopenonlyRead = false
      }
    }
  };
</script>
